/*
 * Copyright (C) Francisco Morero Peyrona. All rights reserved.
 *
 * This software is published under the terms of Open Source
 * License version 1.1, a copy of which has been included with this
 * distribution in the License.txt file.
 */
 
package jdbcmanager.dbtools.agentwise;

import java.io.*;
import java.net.*;

import jdbcmanager.app.*;

/**
 * Load agents at run-time (MetaData Agent & SQL Agent) as they are described in *.dbms file.
 * 
 * @author f.morero
 */
final class AgentLoader
{
   private String sJAR;  // JAR file anme where classes are stored. Can be null.
   
   /**
    * Zero argument constructor
    */
   AgentLoader()
   {
      this( null );   
   }
   
   /**
    * Constructor.
    * 
    * @param sJAR Where agents are stored.
    */
   AgentLoader( String sJAR )
   {
      this.sJAR = sJAR;
   }
   
   /**
    * Return a new instance of desired MetaData Agent.
    * 
    * @param sClassName
    * @return A new instance of desired MetaData Agent.
    * @throws InstantiationException
    * @throws IllegalAccessException
    */
   AgentMetaData loadMeta( String sClassName )
      throws InstantiationException, IllegalAccessException, ClassNotFoundException
   {
      Class clazz = load( sClassName );
      
      if( clazz == null )
         throw new ClassNotFoundException( sClassName );
          
      return (AgentMetaData) clazz.newInstance();
   }
   
   /**
    * Return a new instance of desired SLQ Agent.
    * 
    * @param sClassName
    * @return A new instance of desired SQL Agent.
    * @throws InstantiationException
    * @throws IllegalAccessException
    */
   AgentSQL loadSQL( String sClassName ) 
      throws InstantiationException, IllegalAccessException, ClassNotFoundException
   {
      Class clazz = load( sClassName );
   
      if( clazz == null )
         throw new ClassNotFoundException( sClassName );
          
      return (AgentSQL) clazz.newInstance();
   }
   
   //-------------------------------------------------------------------------//
   
   private Class load( String sClass ) throws ClassNotFoundException
   {
      Class clazz = null;
         
      if( this.sJAR != null )
      {
         try
         {
            File           file = new File( this.sJAR );
            URLClassLoader ucl  = new URLClassLoader( new URL[] { file.toURL() } );
            
            clazz = ucl.loadClass( sClass );
         }
         catch( MalformedURLException exc )
         {
            App.showDebugException( exc );
         }
      }
      else
      {
         String sDir = App.getAgentsDir().getName();
         
         if( sClass.endsWith( ".class" ) )
            sClass = sClass.substring( 0, sClass.lastIndexOf( ".class" ) );
         
         FileClassLoader fcl = new FileClassLoader( sDir );
         clazz = fcl.loadClass( sDir +'.'+ sClass, true );
      }
      
      return clazz;
   }
}